using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace Tools
{
    /// <summary>
    /// 通用工具类
    /// </summary>
    public class Utils
    {

        #region 禁止程序重复启动
        /// <summary>
        /// 检查指定名称的应用程序是否已打开
        /// </summary>
        /// <param name="appName">应用程序名称</param>
        /// <returns>如果应用程序已打开则返回true，否则返回false</returns>
        public static bool IsAppOpened(string appName)
        {
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(appName); //获取指定的进程名
            
            if (myProcesses.Length > 1) //如果可以获取到指定的进程名则说明已经启动
            {
                System.Windows.MessageBox.Show("程序已启动，请勿重新打开！", "提示信息");
                return true;
            }
            
            return false;
        }
        #endregion

        #region 开机自启(通过创建快捷方式到启动目录，不需要管理员权限)
        /// <summary>
        /// 创建快捷方式到启动目录，实现开机自启动
        /// </summary>
        /// <param name="directory">快捷方式路径</param>
        /// <param name="shortcutName">快捷方式名称</param>
        /// <param name="targetPath">可执行文件路径</param>
        /// <param name="description">快捷方式描述</param>
        /// <param name="iconLocation">图标路径</param>
        /// <returns>创建是否成功</returns>
        public static bool CreateAutoStart(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
        {
            try
            {
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                //添加引用 Com 中搜索 Windows Script Host Object Model
                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
                IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
                IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath); //创建快捷方式对象
                shortcut.TargetPath = targetPath; //指定目标路径
                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); //设置起始位置
                shortcut.WindowStyle = 1; //设置运行方式，默认为常规窗口
                shortcut.Description = description; //设置备注
                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation; //设置图标路径
                shortcut.Save(); //保存快捷方式

                return true;
            }
            catch
            {
                // 发生异常时返回false
            }
            return false;
        }

        /// <summary>
        /// 删除开机自启动快捷方式
        /// </summary>
        /// <param name="directory">快捷方式所在目录</param>
        /// <param name="shortcutName">快捷方式名称</param>
        public static void DeleteAutoStart(string directory, string shortcutName)
        {
            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
            if (File.Exists(shortcutPath))
            {
                File.Delete(shortcutPath);
            }
        }

        /// <summary>
        /// 检查是否已设置开机自启
        /// </summary>
        /// <param name="directory">快捷方式所在目录</param>
        /// <param name="shortcutName">快捷方式名称</param>
        /// <returns>是否已设置开机自启</returns>
        public static bool IsAutoStart(string directory, string shortcutName)
        {
            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
            return File.Exists(shortcutPath);
        }
        #endregion

        #region 初始化托盘
        /// <summary>
        /// 初始化系统托盘图标
        /// </summary>
        /// <param name="clickHandler">鼠标点击事件处理器</param>
        /// <param name="openHandler">打开菜单项点击事件处理器</param>
        /// <param name="closeHandler">退出菜单项点击事件处理器</param>
        /// <returns>创建的NotifyIcon对象</returns>
        public static NotifyIcon InitializeTray(MouseEventHandler clickHandler, EventHandler openHandler, EventHandler closeHandler)
        {
            // 创建托盘图标对象
            NotifyIcon notifyIcon = new NotifyIcon
            {
                //BalloonTipText = "服务运行中...",//托盘气泡显示内容
                Text = "BingAuto",
                Visible = true,//托盘按钮是否可见
                Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath)
            };
            //notifyIcon.ShowBalloonTip(2000);//托盘气泡显示时间
            notifyIcon.MouseClick += clickHandler;

            //创建上下文菜单
            ContextMenuStrip contextMenu = new ContextMenuStrip();

            //打开菜单项
            ToolStripMenuItem openItem = new ToolStripMenuItem("打开");
            openItem.Click += openHandler;
            contextMenu.Items.Add(openItem);

            //退出菜单项
            ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
            exitItem.Click += closeHandler;
            contextMenu.Items.Add(exitItem);

            //关联托盘控件
            notifyIcon.ContextMenuStrip = contextMenu;
            
            return notifyIcon;
        }
        #endregion

        #region 更换系统壁纸
        /// <summary>  
        /// 设置Windows桌面背景图片  
        /// </summary>  
        /// <param name="fileUrl">图片文件路径</param>  
        /// <returns>操作结果，非零表示成功</returns>
        public static int SetDesktopImage(string fileUrl)
        {
            int result = 0;
            
            // Windows 7及更早版本只支持BMP格式
            if (Environment.OSVersion.Version.Major < 6 ||
                (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor < 2))
            {
                if (File.Exists(fileUrl))
                {
                    if (Path.GetExtension(fileUrl).ToLower() != ".bmp")
                    {
                        // 其他格式文件先转换为BMP再设置  
                        string tempFile = fileUrl.Substring(0, fileUrl.LastIndexOf('.')) + ".bmp";
                        
                        using (Image image = Image.FromFile(fileUrl))
                        {
                            image.Save(tempFile, System.Drawing.Imaging.ImageFormat.Bmp);
                        }
                        
                        fileUrl = tempFile;
                        result = SystemParametersInfo(20, 0, fileUrl, 2);
                        
                        // 清理临时文件
                        if (File.Exists(tempFile))
                        {
                            File.Delete(tempFile);
                        }
                    }
                    else
                    {
                        result = SystemParametersInfo(20, 0, fileUrl, 2);
                    }
                }
            }
            else
            {
                // Windows 8及以上版本支持更多图片格式
                if (File.Exists(fileUrl))
                {
                    result = SystemParametersInfo(20, 1, fileUrl, 1);
                }
            }
            
            return result;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
                    int uAction,
                    int uParam,
                    string lpvParam,
                    int fuWinIni
                );
        #endregion

        #region 网络请求
        /// <summary>
        /// 获取指定URL的HTML源代码
        /// </summary>
        /// <param name="url">要获取HTML的URL地址</param>
        /// <returns>HTML源代码字符串，如果失败则返回空字符串</returns>
        public static string GetHtml(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return string.Empty;
            }
            try
            {
                // 使用Task.Run确保同步行为，保持与原方法的一致性
                var task = Task.Run(async () =>
                {
                    // 创建局部HttpClient实例
                    using (var client = new HttpClient())
                    {
                        // 设置与原全局HttpClient相同的配置
                        client.Timeout = TimeSpan.FromSeconds(5);  // 设置5秒超时
                        client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");

                        using (HttpResponseMessage response = await client.GetAsync(url))
                        {
                            response.EnsureSuccessStatusCode();
                            // 读取响应内容
                            return await response.Content.ReadAsStringAsync();
                        }
                    }
                });

                // 等待任务完成或超时
                if (task.Wait(5000))
                {
                    // 任务成功完成，返回结果
                    return task.Result;
                }
                else
                {
                    // 任务超时，返回空字符串
                    return string.Empty;
                }
            }
            catch (Exception)
            {
                // 发生异常时返回空字符串
                return string.Empty;
            }
        }

        #endregion

        #region 下载文件
        /// <summary>
        /// 通用文件下载方法
        /// </summary>
        /// <param name="url">文件的URL</param>
        /// <param name="filePath">保存文件的路径</param>
        /// <param name="timeout">超时时间（默认2秒）</param>
        /// <param name="userAgent">用户代理字符串</param>
        /// <returns>是否下载成功</returns>
        public static bool DownloadFile(string url, string filePath, TimeSpan? timeout = null, string userAgent = null)
        {
            try
            {
                // 创建任务，使用HttpClient下载文件
                var task = Task.Run(async () =>
                {
                    // 创建一个新的HttpClient实例
                    using (var client = new HttpClient())
                    {
                        // 设置超时时间，默认为2秒
                        client.Timeout = timeout ?? TimeSpan.FromSeconds(2);
                        
                        // 设置User-Agent，如果未提供则使用默认值
                        if (!string.IsNullOrEmpty(userAgent))
                        {
                            client.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
                        }
                        else
                        {
                            client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER");
                        }
                        
                        // 下载文件并直接写入文件
                        using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                        {
                            response.EnsureSuccessStatusCode();
                            
                            using (var stream = await response.Content.ReadAsStreamAsync())
                            using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                // 使用512字节缓冲区进行读写
                                byte[] buffer = new byte[512];
                                int bytesRead;
                                
                                while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                                {
                                    await fileStream.WriteAsync(buffer, 0, bytesRead);
                                }
                            }
                        }
                    }
                    
                    return true;
                });

                // 等待任务完成或超时
                int timeoutMs = (int)(timeout ?? TimeSpan.FromSeconds(2)).TotalMilliseconds;
                if (task.Wait(timeoutMs))
                {
                    // 任务成功完成，返回结果
                    return task.Result;
                }
                else
                {
                    // 任务超时
                    return false;
                }
            }
            catch (Exception)
            {
                // 发生异常，返回false
                return false;
            }
        }
        #endregion

        #region 加载图片
        /// <summary>
        /// 加载图片，自动识别URL是网络链接还是本地路径
        /// </summary>
        /// <param name="path">图片路径（本地路径或网络URL）</param>
        /// <returns>BitmapImage对象</returns>
        public static BitmapImage LoadImage(string path)
        {
            BitmapImage bitmap = new BitmapImage();

            try
            {
                // 初始化BitmapImage对象
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad; // 确保图片被立即加载

                // 判断是否为网络URL
                if (Uri.TryCreate(path, UriKind.Absolute, out Uri uriResult) && 
                    (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps))
                {
                    // 网络URL处理
                    bitmap.UriSource = uriResult;
                }
                else
                {
                    // 本地路径处理
                    if (File.Exists(path))
                    {
                        bitmap.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
                    }
                    else
                    {
                        // 文件不存在，返回空的BitmapImage
                        bitmap.EndInit();
                        return bitmap;
                    }
                }

                bitmap.EndInit();
                bitmap.Freeze(); // 冻结以提高性能
            }
            catch (Exception)
            {
                // 处理异常（例如图片加载失败）
                // 不抛出异常，返回空的BitmapImage
            }

            return bitmap;
        }
        #endregion
    }
}